package tech.eyao.hs60x.token;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import tech.eyao.hs60x.common.ConstantsKey;

/**
 * redis token
 * @author hejian
 * @date 2017年12月18日 下午7:13:02
 */
@Component
public class RedisTokenManager extends AbstractTokenManager {
	
	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	private static final Logger logger = LoggerFactory.getLogger(RedisTokenManager.class);
	
	/**
	 * 生成token
	 * @param userId
	 * @param deviceId
	 * @return
	 */
	public String acquireToken(long userId,String deviceId) {
		String token =super.createToken(userId,deviceId);
		if(StringUtils.isNotEmpty(token)) {
			try {
				redisTemplate.opsForValue().set(ConstantsKey.getUserTokenKey(userId), token);
			} catch (Exception e) {
				logger.error("[RedisTokenManager acquireToken userId ]" + userId,e);
			}
		}
		return token;
	}
	
	/**
	 * 查询token 
	 * @param userId
	 * @return
	 */
	public String getToken(long userId) {
		try {
			return redisTemplate.opsForValue().get(ConstantsKey.getUserTokenKey(userId));
		} catch (Exception e) {
			logger.error("[RedisTokenManager acquireToken userId ]" + userId,e);
		}
		return null;
	}

	@Override
	public void verifyExpired() {
	}

	@Override
	public void addToken(String token, Object loginUser) {
	}

	@Override
	public Object validate(String token) {
		return null;
	}

	@Override
	public void remove(String token) {
		
	}

	/**
	 * 删除key
	 * @param userId
	 */
	public void deleteOldToken(Long userId) {
		try {
			 redisTemplate.delete(ConstantsKey.getUserTokenKey(userId));
		} catch (Exception e) {
			logger.error("[RedisTokenManager deleteOldToken userId ]" + userId,e);
		}
	}

}
